import { CanvasButton } from '../component/custombutton'
import { env } from "../../.eslintrc";
export class Activity{
  constructor(canvas, width, height, continueCallback){
    this.canvas = canvas;
    this.context = this.canvas.getContext('2d');
    this.width = width;
    this.height = height;
    this.continueCallback = continueCallback;

    this.cloud = false;
    this.isAnimating = true;
    this.signIn = wx.getStorageSync('signIn');
    this.nowDay = wx.getStorageSync('nowDay');
    this.maxDay = 7;

    this.button = [];
    this.onLoadImage(() => {
      this.drawButton();
      this.drawPopup();
    })
  }

    drawPopup() {
      this.isAnimating = true;
      this.drawAnimate();
      
  }

  drawButton() {
    let _this = this;
    let close = {
      type: 'image',
      image: 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/close.png',
      style: {
        left: _this.width / 100 * 81,
        top: _this.height / 100 * 20,
        width: 50,
        height: 50,
      },
      success(button) {
        console.log('关闭按钮创建成功');
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => { // 点击事件
          if (typeof _this.continueCallback === 'function') {
            _this.getsignIn();
            _this.isAnimating = false;
            _this.continueCallback();
            for(let i = 0; i < _this.button.length; i++){
              _this.button[i].destroy();
            }
            _this.getSkinsInfo();
          }
        });
      },
      fail(res) {
        console.log("创建失败", res.errMsg);
      }
    }
    new CanvasButton(close);
    if(this.nowDay === 7){
      let geter = {
        type: 'text',
        text: '您已获得',
        style: {
          left: _this.width / 100 * 35,
          top: _this.height / 100 * 62,
          width: _this.width / 100 * 30,
          height: _this.height / 100 * 5,
          backgroundColor: 'red',
          borderRadius: 25
        },
        success(button) {
          console.log('您已获得按钮创建成功');
          _this.button.push(button);
          button.drawButton(_this.context); // 绘制按钮
          button.onTap((res) => { // 点击事件
            wx.showToast({
              title: '您已获得该皮肤，快到背包装备吧',
              icon: 'none',
              success: (res) => {
              },
              fail: (res) => {
                wx.offTouchStart();
              }
            })
          });
        },
        fail(res) {
          console.log("创建失败", res.errMsg);
        }
      }
      new CanvasButton(geter);
    } else if (!_this.signIn) {
      console.log(_this.signIn)
      let signIn = {
        type: 'text',
        text: '签  到',
        style: {
          left: this.width / 100 * 35,
          top: this.height / 100 * 62,
          width: this.width / 100 * 30,
          height: this.height / 100 * 5,
          backgroundColor: 'yellow',
          borderRadius: 25
        },
        success(button) {
          console.log('签到按钮创建成功');
          _this.button.push(button);
          button.drawButton(_this.context); // 绘制按钮
          button.onTap((res) => { // 点击事件
            _this.nowDay++;
            wx.cloud.init({
              env: 'prod-8gf88ck5bb3ddd38'
            })
            wx.cloud.callContainer({
              "config": {
                "env": "prod-8gf88ck5bb3ddd38"
              },
              "path": "apis/sign/userSignIn",
              "header": {
                'content-type': 'application/json',
                'AuthToken': wx.getStorageSync("AuthToken"),
                "X-WX-SERVICE": env.service
              },
              "method": "POST",
              success: (res) => {
                console.log(res);
              },
              fail: console.warn,
            })
            console.log(_this.nowDay);
            button.hideButton();
            let signInLater = {
              type: 'text',
              text: '今日已签到',
              style: {
                left: _this.width / 100 * 35,
                top: _this.height / 100 * 62,
                width: _this.width / 100 * 30,
                height: _this.height / 100 * 5,
                backgroundColor: 'green',
                borderRadius: 25
              },
              success(button) {
                console.log('签到完成按钮创建成功');
                _this.button.push(button);
                button.drawButton(_this.context); // 绘制按钮
                button.onTap((res) => { // 点击事件
                  wx.showToast({
                    title: '今日已签到，明天再来吧',
                    icon: 'none',
                    success: (res) => {
      
                    },
                    fail: (res) => {
                      wx.offTouchStart();
                    }
                  })
                });
              },
              fail(res) {
                console.log("创建失败", res.errMsg);
              }
            }
            new CanvasButton(signInLater);
          });
        },
        fail(res) {
          console.log("创建失败", res.errMsg);
        }
      }
      new CanvasButton(signIn);
    } else {
      let signInLater = {
        type: 'text',
        text: '今日已签到',
        style: {
          left: _this.width / 100 * 35,
          top: _this.height / 100 * 62,
          width: _this.width / 100 * 30,
          height: _this.height / 100 * 5,
          backgroundColor: 'green',
          borderRadius: 25
        },
        success(button) {
          console.log('签到完成按钮创建成功');
          _this.button.push(button);
          button.drawButton(_this.context); // 绘制按钮
          button.onTap((res) => { // 点击事件
            wx.showToast({
              title: '今日已签到，明天再来吧',
              icon: 'none',
              success: (res) => {

              },
              fail: (res) => {
                wx.offTouchStart();
              }
            })
          });
        },
        fail(res) {
          console.log("创建失败", res.errMsg);
        }
      }
      new CanvasButton(signInLater);
    }
  }

  drawAnimate(){
    if(this.isAnimating){
        this.context.drawImage(this.background, this.width / 100 * 1, this.height / 100 * 10, this.width / 100 * 98, this.height / 100 * 80);
        this.context.drawImage(this.skin, this.width / 100 * 10, this.height / 100 * 38, this.width / 100 * 65, this.height / 100 * 30);
        this.context.fillStyle = 'green'
        //this.context.fillRect(this.width / 100 * 10, this.height / 100 * 22, this.width / 100 * 80, this.height / 100 * 50)
          this.drawSegmentedRoundedRect(this.context, this.width / 100 * 78, this.height / 100 * 35, 20, this.height / 100 * 25, 20, this.nowDay);
          if(this.nowDay === this.maxDay){
            this.context.fillStyle = 'black';
            this.context.font = '900 18px Arial'
            this.context.fillText('m', this.width / 100 * 81, this.height / 100 * 47 - 20);
            this.context.fillText('a', this.width / 100 * 81, this.height / 100 * 47 );
            this.context.fillText('x', this.width / 100 * 81, this.height / 100 * 47 + 20);
          } else {
            this.context.fillStyle = 'black';
            this.context.font = '800 16px Arial'
            this.context.fillText(`${this.nowDay}`, this.width / 100 * 81, this.height / 100 * 47 - 20);
            this.context.fillText(`/`, this.width / 100 * 81, this.height / 100 * 47);
            this.context.fillText(`${this.maxDay}`, this.width / 100 * 81, this.height / 100 * 47 + 20);
          }
    }
    requestAnimationFrame(() => this.drawAnimate());
  }

  drawRoundedRect(context, x, y, width, height, radius, color, borderWidth, borderColor) {
    context.beginPath();
    radius = Math.min(radius, width / 2, height / 2);
    
    context.moveTo(x + radius, y);
    context.lineTo(x + width - radius, y);
    context.arcTo(x + width, y, x + width, y + height, radius);
    context.lineTo(x + width, y + height - radius);
    context.arcTo(x + width, y + height, x, y + height, radius);
    context.lineTo(x + radius, y + height);
    context.arcTo(x, y + height, x, y, radius);
    context.lineTo(x, y + radius);
    context.arcTo(x, y, x + width, y, radius);
    
    context.closePath();
    
    // 填充颜色
    context.fillStyle = color;
    context.fill();
    
    // 绘制边框
    context.lineWidth = borderWidth;
    context.strokeStyle = borderColor;
    context.stroke();
  }

  drawSegmentedRoundedRect(context, x, y, width, height, radius, energy) {
    // 绘制背景圆角矩形
    this.drawRoundedRect(context, x, y, width, height, radius, 'rgba(128,128,128,0)', 1, 'black');
    
    // 计算填充的部分宽度
    const filledHeight = (energy / this.maxDay) * height;

    // 清除填充部分的区域
    context.save();
    context.globalCompositeOperation = 'destination-out'; // 只清除绘制区域
    context.beginPath();
    context.moveTo(x + radius, y);
    context.lineTo(x + width - radius, y);
    context.arcTo(x + width, y, x + width, y + filledHeight, radius);
    context.lineTo(x + width, y + filledHeight - radius);
    context.arcTo(x + width, y + filledHeight, x, y + filledHeight, radius);
    context.lineTo(x + radius, y + filledHeight);
    context.arcTo(x, y + filledHeight, x, y, radius);
    context.lineTo(x, y + radius);
    context.arcTo(x, y, x + width, y, radius);
    context.closePath();
    context.fill(); // 清除指定区域
    context.restore();

    // 绘制完整的圆角矩形
    context.save();
    context.beginPath();
    context.translate(x, y); // 移动到矩形左上角

    if(energy < this.maxDay){
      var color = 'rgba(0, 255, 0, 0.7)';
    } else {
      color = 'red';
    }
    // 绘制填充部分的圆角矩形
    if(energy>0)
      this.drawRoundedRect(context, 0, 0, width, filledHeight, radius, color, 1, 'black');
    context.restore();
  }

  getsignIn(){
    wx.cloud.init({
      env: 'prod-8gf88ck5bb3ddd38'
    })
    wx.cloud.callContainer({
      "config": {
        "env": "prod-8gf88ck5bb3ddd38"
      },
      "path": "/apis/sign/signIndays",
      "header": {
        'content-type': 'application/json',
        'AuthToken': wx.getStorageSync("AuthToken"),
        "X-WX-SERVICE": env.service
      },
      "method": "GET",
      success: (res) => {
        console.log(res);
        this.nowDay = res.data.signIndays;
        this.signIn = res.data.todayIsSigned;
        wx.setStorageSync('nowDay', this.nowDay);
        wx.setStorageSync('signIn', this.signIn);
      },
      fail: console.warn,
    })
  }

  onLoadImage(callback) {
    let loadedCount = 0;
    const totalImages = 2;

    this.background = wx.createImage();
    this.background.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/signIn.png'; // 替换为你的背景图片路径
    this.background.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.skin = wx.createImage();
    this.skin.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/skins/skin_19.png'; // 替换为你的背景图片路径
    this.skin.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    const checkIfAllLoaded = () => {
      if (loadedCount === totalImages && callback) {
        callback();
      }
    };
  }
  getSkinsInfo() {
    wx.cloud.callContainer({
      "config": {
        "env": "prod-8gf88ck5bb3ddd38"
      },
      "path": `/apis/skin/selectUserSkins`,
      "header": {
        'content-type': 'application/json',
        'AuthToken': wx.getStorageSync("AuthToken"),
        "X-WX-SERVICE": env.service
      },
      "method": "GET",
      success: (res) => {
        console.log(res.data.skinInfo);
        wx.setStorage({
          key: 'skinInfo',
          data: res.data.skinInfo,
          success: function (res) {
            console.log('skin success');
          },
          fail: function (err) {
            console.error('skin seccess', err);
          }
        });
      },
      fail: console.warn,
    })
  }
}